/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.kaoqin.rest;

import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.kaoqin.domain.Kaoqin;
import me.zhengjie.modules.kaoqin.domain.attention;
import me.zhengjie.modules.kaoqin.repository.AttentionRepository;
import me.zhengjie.modules.kaoqin.repository.KaoqinRepository;
import me.zhengjie.modules.kaoqin.service.KaoqinService;
import me.zhengjie.modules.kaoqin.service.dto.KaoqinQueryCriteria;
import me.zhengjie.modules.reply.domain.ReplyCount;
import me.zhengjie.modules.reply.repository.ReplyCountRepository;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import me.zhengjie.utils.PageResult;
import me.zhengjie.modules.kaoqin.service.dto.KaoqinDto;

import static org.apache.commons.lang3.StringUtils.capitalize;

/**
* @website https://eladmin.vip
* @author wzy
* @date 2024-11-17
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "kao管理")
@RequestMapping("/api/kaoqin")
public class KaoqinController {

    private final KaoqinService kaoqinService;
    private final KaoqinRepository kaoqinRepository;
    private  final AttentionRepository attentionRepository;
    @PostMapping("/updatecorce/{corce}")
    @AnonymousAccess
    public ResponseEntity<Object> updatacor(@PathVariable("corce") Integer corce) {

        System.out.println(corce);
        List<attention> a = attentionRepository.findAll();
        for (attention data : a) {
            data.setSum(corce);
            attentionRepository.save(data);
        }
        return ResponseEntity.ok("更新成功");
    }
    @GetMapping(value = "/attendance/{studentid}")
    @AnonymousAccess
    public ResponseEntity<List<Map<String, Object>>> getAttendanceByStudentId(@PathVariable("studentid") Integer studentid) {
        try {
            // 调用服务层获取考勤数据
            List<Map<String, Object>> attendanceData = attentionRepository.getAttendanceByStudentId(studentid);
            System.out.println(attendanceData);
            return ResponseEntity.ok(attendanceData);

        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
   Integer getA(String value) {
        switch (value) {
            case "正常":
                return 1;
            case "迟到":
                return 2;
            case "缺席":
                return 3;
            default:
                return 4;
        }
    }
    public String Getsocre(){
        List<attention> record = attentionRepository.findAll();
        Integer sum = 0;
        for (attention data : record) {
            for (int i = 1; i <= data.getSum(); i++) {
                Integer value = null;

                // Use reflection to get the corresponding field dynamically (data1, data2, ..., data20)
                try {
                    // Construct the field name dynamically (e.g., "data1", "data2", ..., "data20")
                    String fieldName = "data" + i;
                    // Get the field value using reflection
                    value = (Integer) data.getClass().getMethod("get" + capitalize(fieldName)).invoke(data);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // Check the value and increment the count
                if (value != null) {
                    if (value == 1) {
                        sum=sum+1;
                    } else if (value == 2) {
                       sum=sum+2;
                    } else if(value ==3){
                        sum=sum+3;
                    }else {
                        sum=sum+4;
                    }
                }
            }
            System.out.println(sum);
        }

        return "";
    }
    @PostMapping("/gradeRules")
    @AnonymousAccess
    public ResponseEntity<Object> saveGrade(@RequestBody Map<String, Object> rule) {

            Integer normal = Integer.parseInt(rule.get("normal").toString());
            Integer absent = Integer.parseInt(rule.get("absent").toString());
            Integer sickLeave = Integer.parseInt(rule.get("sickLeave").toString());
            Integer late = Integer.parseInt(rule.get("late").toString());

            // Find all entries with the same count and update their points
        List<attention> record = attentionRepository.findAll();

        for (attention data : record) {
            Integer sum = 0;
            for (int i = 1; i <= data.getSum(); i++) {
                Integer value = null;
                // Use reflection to get the corresponding field dynamically (data1, data2, ..., data20)
                try {
                    // Construct the field name dynamically (e.g., "data1", "data2", ..., "data20")
                    String fieldName = "data" + i;
                    // Get the field value using reflection
                    value = (Integer) data.getClass().getMethod("get" + capitalize(fieldName)).invoke(data);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // Check the value and increment the count
                if (value != null) {
                    if (value == 1) {
                        sum=sum+normal;
                    } else if (value == 2) {
                        sum=sum+late;
                    } else if(value ==3){
                        sum=sum+absent;
                    }else {
                        sum=sum+sickLeave;
                    }
                }
            }
            Kaoqin m =kaoqinRepository.findByStudentid(data.getStudentid());
            m.setGrade(sum);
            kaoqinRepository.save(m);
            System.out.println(sum);
        }
//            List<ReplyCount> replies = ReplyCountRepository.findAllByCount(count);
//            for (ReplyCount reply : replies) {
//                reply.setGrade(points); // Ensure the ReplyCount entity has a `points` field
//                ReplyCountRepository.save(reply);
//            }
//
        return ResponseEntity.ok("已更新");
    }
    @PostMapping(value = "/attendance/{studentid}")
    @AnonymousAccess
    public ResponseEntity<String> saveAttendanceByStudentId(
            @PathVariable("studentid") String studentid,
            @RequestBody List<Map<String, Object>> attendanceData) {
        try {
            System.out.println(attendanceData);
            // 调用服务层将考勤数据保存到数据库
            attention record = attentionRepository.findByStudentid(Integer.valueOf(studentid));
            for (Map<String, Object> data : attendanceData) {
                Integer id = (Integer) data.get("id");
                String value = (String) data.get("value");
                System.out.println(id);
                Integer m = null;
                m=getA(value);
                // Set the corresponding field based on the id value
                switch (id) {
                    case 1:
                        record.setData1(m);
                        break;
                    case 2:
                        record.setData2(m);
                        break;
                    case 3:
                        record.setData3(m);
                        break;
                    case 4:
                        record.setData4(m);
                        break;
                    case 5:
                        record.setData5(m);
                        break;
                    case 6:
                        record.setData6(m);
                        break;
                    case 7:
                        record.setData7(m);
                        break;
                    case 8:
                        record.setData8(m);
                        break;
                    case 9:
                        record.setData9(m);
                        break;
                    case 10:
                        record.setData10(m);
                        break;
                    case 11:
                        record.setData11(m);
                        break;
                    case 12:
                        record.setData12(m);
                        break;
                    case 13:
                        record.setData13(m);
                        break;
                    case 14:
                        record.setData14(m);
                        break;
                    case 15:
                        record.setData15(m);
                        break;
                    case 16:
                        record.setData16(m);
                        break;
                    case 17:
                        record.setData17(m);
                        break;
                    case 18:
                        record.setData18(m);
                        break;
                    case 19:
                        record.setData19(m);
                        break;
                    case 20:
                        record.setData20(m);
                        break;
                    case 21:
                        record.setData21(m);
                        break;
                    case 22:
                        record.setData22(m);
                        break;
                    case 23:
                        record.setData23(m);
                        break;
                    case 24:
                        record.setData24(m);
                    case 25:
                        record.setData25(m);
                        break;

                    // Add more cases as needed for other ids
                    default:
                        break;
                }
            }

            // Save the updated record back to the database
            attentionRepository.save(record);
          // boolean isSaved = attentionRepository.saveAttendanceByStudentId(studentid, attendanceData);
            boolean isSaved =true;
            if (isSaved) {
                return ResponseEntity.ok("考勤数据保存成功！");
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("考勤数据保存失败！");
            }
        } catch (Exception e) {
            // 打印错误日志以供调试
            e.printStackTrace();
            return new ResponseEntity<>("服务器内部错误，考勤数据保存失败！", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('kaoqin:list')")
    public void exportKaoqin(HttpServletResponse response, KaoqinQueryCriteria criteria) throws IOException {
        //Getsocre();
        kaoqinService.download(kaoqinService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询kao")
    @ApiOperation("查询kao")
    @PreAuthorize("@el.check('kaoqin:list')")
    public ResponseEntity<PageResult<KaoqinDto>> queryKaoqin(KaoqinQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(kaoqinService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增kao")
    @ApiOperation("新增kao")
    @PreAuthorize("@el.check('kaoqin:add')")
    public ResponseEntity<Object> createKaoqin(@Validated @RequestBody Kaoqin resources){
        kaoqinService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改kao")
    @ApiOperation("修改kao")
    @PreAuthorize("@el.check('kaoqin:edit')")
    public ResponseEntity<Object> updateKaoqin(@Validated @RequestBody Kaoqin resources){
        kaoqinService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除kao")
    @ApiOperation("删除kao")
    @PreAuthorize("@el.check('kaoqin:del')")
    public ResponseEntity<Object> deleteKaoqin(@RequestBody Integer[] ids) {
        kaoqinService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
